<template>
  <div class="login">
    <el-dialog v-model="isVisible" width="30%" :before-close="handleClose">
      <div class="login-wrapper">
        <div class="login-logo">
          <img src="@/assets/img/logo-light.png" v-if="ischunyilv" alt="bbb" />
          <img src="@/assets/img/logo-chunyilv.png" v-else alt="bbb" />
          <span>网易云音乐</span>
        </div>
        <div v-if="imgLogin" class="erweima">
          <img :src="imgUrl" alt="bbb" />
        </div>
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
          <el-form-item prop="email" label-width="" v-show="!imgLogin">
            <el-input v-model="loginForm.email" placeholder="请输入网易邮箱登录"></el-input>
          </el-form-item>
          <el-form-item prop="password" label-width="" v-show="!imgLogin">
            <el-input v-model="loginForm.password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item v-show="!imgLogin">
            <el-button type="primary" @click="submitForm" class="login-btn">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="tiggerType" class="login-btn">{{ loginType }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Login">
import { computed, getCurrentInstance, onBeforeUnmount, reactive, ref, watch } from "vue";
import { useUserStore } from "@/store/UserStore";
import api from "@/assets/apis/instance";
import {getUserInfo} from "@/assets/apis/http";
import {useRouter} from "vue-router";
import util from "@/tools/util";

const router = useRouter();
const store = useUserStore();
const isVisible = computed(() => {
  // console.log("Dialog Visibility:", store.loginDialogVisible);
  return store.loginDialogVisible;
});
const ischunyilv = computed(() => store.currentTheme === "chunyilv");

const loginForm = reactive({
  email: "",
  password: ""
});
let imgLogin = ref(false);
const loginType = computed(() => {
  return imgLogin.value ? "邮箱登录" : "扫码登录";
});
const loginFormRules = {
  email: [{ required: true, message: "请输入网易邮箱", trigger: "blur" }],
  password: [{ required: true, message: "请输入邮箱密码", trigger: "blur" }]
};

const { proxy } = getCurrentInstance();
const loginFormRef = ref(null);
const imgUrl = ref("");

const handleClose = () => {
  store.loginDialogVisible = false;
};

function tiggerType() {
  imgLogin.value = !imgLogin.value;
}

const submitForm = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const { data: res } = await api.post("/login", loginForm);
        if (res.code !== 200) {
          proxy.$msg.error(res.message);
        } else {
          await getUserInfof(res.profile.userId); // 确保获取用户信息
          window.localStorage.setItem("token", res.token);
          window.localStorage.setItem("cookie", res.cookie);
          store.loginDialogVisible = false;
        }
      } catch (error) {
        proxy.$msg.error("登录请求失败，请重试。");
        console.error(error);
      }
    }
  });
};

//创建登录二维码
let timer;

async function createImg() {
  const { data: res } = await api.get("/login/qr/key");
  console.log("二维码key", res);
  const { data: res2 } = await api.get("/login/qr/create?qrimg=true&key=" + res.unikey);
  console.log("二维码图片", res2);
  imgUrl.value = res2.qrimg;
  timer = setInterval(async () => {
    const statusRes = await checkStatus(res.unikey);
    console.log("扫码结果", statusRes);
    if (statusRes.code === 800) {
      alert("二维码已过期,请重新获取");
      clearInterval(timer);
      await createImg()
    } else if (statusRes.code === 803) {
      clearInterval(timer);
      await getLoginStatus(statusRes.cookie);
      localStorage.setItem("cookie", statusRes.cookie);
    }
  }, 3000);
}

//获取登陆状态
async function getLoginStatus(cookie = "") {
  api.post(`/login/status?timestamp=${Date.now()}`, cookie).then((res) => {
    console.log(JSON.stringify(res.data));
    store.userInfo = res.data.profile;
    store.loginDialogVisible = false;
    store.isLogin = true;
    router.go(0)
  });
}

async function checkStatus(key) {
  return await api.get(`/login/qr/check?key=${key}&timestamp=${Date.now()}`);
}

onBeforeUnmount(() => {
  clearInterval(timer);
});
watch(isVisible, (newValue, oldValue) => {
  console.log(`myVariable 发生变化: 从 ${oldValue} 变为 ${newValue}`);
  console.log(typeof newValue);
  if (!newValue) {
    clearInterval(timer);
  } else {
    createImg();
  }
});

const getUserInfof = async (uid) => {
    const { data: res } = await getUserInfo({ uid });
    if (res.code !== 200) {
      proxy.$msg.error(res.msg);
    } else {
      store.isLogin = true;
      let profile = res.profile;
      store.userInfo = {
        userId: profile.userId,             // 用户Id
        userType: profile.userType,         // 类型
        nickname: profile.nickname,         // 昵称
        avatarUrl: util.formatSongsPic(profile.avatarUrl,100),       // 头像
        createTime: profile.createTime,     // 创建时间时间戳
        birthday: profile.birthday,         // 生日时间戳
        gender: profile.gender===1?"男":"女",// 性别 1男2女
        province: profile.province,         // 省编码
        city: profile.city,                 // 市编码
        vipType: profile.vipType,           // 是否vip
        license: profile.license,           // 版权信息
        publishTime: profile.publishTime    // 发布时间
      }
      router.go(0)
    }
}
</script>
<style scoped lang="scss">
.login-wrapper {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  .erweima {
    img {
      width: 180px;
    }
  }

  .el-form {
    width: 100%;
  }
}

.login-logo {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1rem;

  img {
    width: 40px;
    margin-right: 1rem;
  }

  span {
    font-size: 30px;
  }
}

.login-btn {
  width: 100%;
}
</style>
